from django.shortcuts import render

# Create your views here.


from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from . import serializers, models


# 课程分类群查 ListModelMixin
class CourseCategoryViewSet(GenericViewSet, ListModelMixin):
    queryset = models.CourseCategory.objects.filter(is_delete=False, is_show=True).all()
    serializer_class = serializers.CourseCategorySerializer


# 分页组件


# 过滤组件：搜索功能、排序功能
from rest_framework.filters import SearchFilter, OrderingFilter

# django-filter插件：分类功能
from django_filters.rest_framework import DjangoFilterBackend
from .filters import CourseFilterSet
from . import paginations


class CourseViewSet(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).all()
    serializer_class = serializers.CourseSerializer

    pagination_class = paginations.PageNumberPagination
    # 加上了这个序列化的数据就有了以下这样的标识，来表示页与页之间的关系。
    '''
    "count": 3,
    "next": "http://127.0.0.1:8001/course/free/?page=2",
    "previous": null,
    '''

    # 过滤的类需要在filter_backends注册才可执行。
    filter_backends = [SearchFilter, OrderingFilter, DjangoFilterBackend]
    # 搜索框专用
    search_fields = ['name', 'id', 'brief']  # 查询时 ？search=  根据这三个字段下的任务记录都可以查询到
    ordering_fields = ['id', 'price', 'students']

    # 点击分类专用，需用专用的key。
    filter_class = CourseFilterSet


# 一个课程的所有章节（群查）
class ChapterViewSet(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    queryset = models.CourseChapter.objects.filter(is_delete=False, is_show=True).all()
    serializer_class = serializers.CourseChapterSerializer

    # 基于课程分类条件下的查询
    filter_backends = [DjangoFilterBackend]
    # 用的默认过滤条件，适合查询的key是model本来就有的字段。
    filter_fields = ['course']


class SearchCourseViewSet(GenericViewSet, ListModelMixin):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).all()

    serializer_class = serializers.CourseSerializer

    pagination_class = paginations.PageNumberPagination

    filter_backends = [SearchFilter]  # 过滤类型在此注册

    search_fields = ['name', 'id']  # 通过模糊匹配课程名，过滤出该课程的数据。
